 #!/bin/bash

# proftpd控制腳本
# 可加入到service服務中進行管理
# 部分功能還有待優化

 FTPD_BIN=/usr/local/proftpd/sbin/proftpd
 FTPD_CONF=/usr/local/proftpd/proftpd.conf
 PIDFILE=/usr/local/proftpd/var/proftpd.pid

 if [ -f $PIDFILE ]; then
    pid=`cat $PIDFILE` 
 fi
 if [ ! -x $FTPD_BIN ]; then
    echo "$0: $FTPD_BIN: cannot execute"
    exit 1
 fi

function startProftp(){
    if [ -n "${PIDFILE}" ]; then
        echo "$0: proftpd [PID $pid] already running"
        exit
    fi
    if [ -r ${FTPD_CONF} ]; then
        echo "Starting proftpd..."
        $FTPD_BIN -c $FTPD_CONF
    else
        echo "$0: cannot start proftpd -- $FTPD_CONF missing"
    fi
}

# 經過測試貌似不添加-DANONYMOUS_FTP參數也能啟動匿名用戶訪問
function startProftpAnon(){
    if [ -n "${PIDFILE}" ]; then
        echo "$0: proftpd [PID $pid] already running"
        exit
    fi
    if [ -r ${FTPD_CONF} ]; then
        echo "Starting proftpd..."
        $FTPD_BIN -c $FTPD_CONF -DANONYMOUS_FTP
    else
        echo "$0: cannot start proftpd -- $FTPD_CONF missing"
    fi
}

function stopProftp(){
    if [ -n "$pid" ]; then
        echo "Stopping proftpd..."
        kill -TERM $pid && rm -f ${PIDFILE}
    else
        echo "$0: proftpd not running"
        exit 1
    fi
}

function reloadProftp(){
    if [ -n "$pid" ]; then
        # 重新加載proftpd.conf配置
        echo "Rehashing proftpd configuration"
        kill -HUP $pid
    else
        echo "$0: proftpd not running"
        exit 1
    fi
}

function checkProftp(){
    local FTPD_PORT=(`/bin/egrep "^Port" ${FTPD_CONF}`)
    local FTPD_PORT_STATUS=`lsof -i:${FTPD_PORT[1]} | grep nobody | wc -l`
    local FTPD_PROC_STATUS=`ps -ef | grep proftpd | grep nobody | wc -l`
    if [[ ${FTPD_PORT_STATUS} == 1 ]] && [[ ${FTPD_PROC_STATUS} == 1 ]];then
        echo "$0: proftpd [PID $pid] already running"
    else
        echo "$0: proftpd not running"
    fi
}

function proftpHelp(){
    echo "usage: $0 {start|start_anon|stop|restart|check}"
    exit 1
}

case $1 in
    start)
        startProftp
        ;;
    start_anon)
        startProftpAnon
        ;;
    stop)
        stopProftp
        ;;
    reload)
        reloadProftp
        ;;
    restart)
        stopProftp
        sleep 5
        startProftp
        ;;
    check)
        checkProftp
        ;;
    *)
        proftpHelp
        ;;
esac
exit 0